﻿using Ldt.DataEngine.DataFlowParse.Model;
using Ldt.InformationUnit.Common;
using LdtDataEngin.ModuleDetail.BaseModule.Optimization;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.Common.ConfigXmlLoad;
using LdtJudge.DataEngine.Common.DataSave;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.Data;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.Collection;
using LdtJudge.DataEngine.Model.CommModel;
using LdtJudge.DataEngine.Model.DataModel.SystemtableModel;
using LdtJudge.DataEngine.Model.EvidenceDerivation;
using LdtJudge.DataEngine.Model.EvidenceFact;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using LdtJudge.DataEngine.Model.XMLConfigModel.OptimizeConfigModel;
using LdtJudge.DataEngine.Model.XMLConfigModel.OptimzeMode;
using LdtJudge.DataEngine.Model.XMLConfigModel.SameNodeConfigModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace LdtDataEngin.ModuleDetail.OptimizationModule.EvidenceDerivation
{
    /// <summary>
    /// 进行证据与事实要素比对
    /// </summary>
    public class EvidenceDerivationClass : OptimizationBase
    {
        #region 基本变量
        /// <summary>
        /// 事实要素集合
        /// </summary>
        private List<DataModel> FactualDataModelList = new List<DataModel>();

        /// <summary>
        /// 合并后要素信息
        /// </summary>
        private List<DataModel> MergerElementModelList = new List<DataModel>();

        /// <summary>
        /// 合并后要素根节点信息
        /// </summary>
        private DataModel MergerElementRoot = new DataModel();

        /// <summary>
        /// 证据要素集合
        /// </summary>
        private List<DataModel> EvidenceDataModelList = new List<DataModel>();

        /// <summary>
        /// 不包含证据要素的证据
        /// </summary>
        private List<DataModel> DataEvidenceList = new List<DataModel>();

        private List<EvidenctFactModel> configInfos = new List<EvidenctFactModel>();

        /// <summary>
        /// 是否WEB应用
        /// </summary>
        public string IsXpath = "";

        /// <summary>
        /// 要素定位配置信息
        /// </summary>
        public DOCLocationModel locationModel { get; set; }

        #endregion

        /// <summary>
        /// 进行证据与事实要素比对
        /// </summary>
        public EvidenceDerivationClass(DataContext dataContext, string moduleName)
        {
            this.dataContext = dataContext;
            this.ModuleName = moduleName;
        }

        /// <summary>
        /// 执行比对
        /// </summary>
        public void ExeComparison()
        {
            Stopwatch stopwatch = new Stopwatch();
            SetModuleProcess(ModuleName, 0, dataContext.InteractiveShow.inputParameterModel);
            stopwatch.Start();
            var config = this.dataContext.DataLayerSys.GetConfigModel(ModuleName);
            string causeLocalContent = string.Empty;
            string causeStageContent = string.Empty;
            ConfigModel causeLocalConfig = config.ConfigDetail.FirstOrDefault(x => x.ExecuteCode == "elementpath.xml");
            if (causeLocalConfig != null)
                causeLocalContent = causeLocalConfig.ConfigContent;
            ConfigModel causeStageConfig = config.ConfigDetail.FirstOrDefault(x => x.Code.ToLower() == "causestagelocation");
            if (causeStageConfig != null)
                causeStageContent = causeStageConfig.ConfigContent;
            var locationModelList = GetLocationModels(causeLocalContent, causeStageContent);
            dataContext.DataLayerSys.locationModelList = locationModelList;

            #region 1.0执行证据关系对应
            try
            {
                EvidenceCorresponding evidenceCorresponding = new EvidenceCorresponding(dataContext, ModuleName);

                if (config.ConfigDetail.FirstOrDefault(a => a.Code.ToLower() == "evidencetypeconfig") != null)
                {
                    //添加案件类型
                    string message = config.ConfigDetail.FirstOrDefault(a => a.Code.ToLower() == "evidencetypeconfig").ConfigContent;
                    EvidenceTypeConfigModel evidenceTypeConfigModel = XmlUtility.DeserializeToObject<EvidenceTypeConfigModel>(message);
                    evidenceCorresponding.Corresponding(evidenceTypeConfigModel);
                }
                //最后阶段数据
                XmlUtilCommon xmlUtilCommon = new XmlUtilCommon();
                var lastStageModel = dataContext.DataLayerSys.locationModelList.FirstOrDefault();
                var evidRootPath = $"{lastStageModel.DocPath}/证据相关信息";
                DataModel evidenRelationNode = XmlUtility.ConditionFirstOrDefaultDataModel(dataContext.DataLayerOpt.SourdatModleList, "", evidRootPath);
                var evidDatas = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, evidenRelationNode);
                if (config.ConfigDetail.FirstOrDefault(a => a.Code.ToLower() == "evidencenameconfig") != null)
                {
                    List<DataModel> datamodeList = evidDatas.Where(x => x.XmlPath.EndsWith("详情") && x.XmlPath.Contains("证据内容") && !x.XmlPath.Contains("证据要素")).ToList();
                    //获取实体证据
                    var entityEvidData = datamodeList.Where(x => x.AttributesList.Any(a => a.Name == "证据形态") && x.AttributesList.FirstOrDefault(a => a.Name == "证据形态").sourceList.Any(s => s.IsCheck == "1" && s.SaveValue == "1")).ToList();
                    if(entityEvidData!=null && entityEvidData.Any())
                    {
                        foreach (var item in entityEvidData)
                        {
                            //实体证据文书编号
                            string eivdSourceCode = item.AttributesList.FirstOrDefault(a => a.Name == "证据文书编号").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                            //实体证据的 证据内容详情节点ID
                            string evidID = item.ID;
                            //添加实体证据与非实体证据关系
                            string message = config.ConfigDetail.FirstOrDefault(a => a.Code.ToLower() == "evidencenameconfig").ConfigContent;
                            EvidenceNameConfig evidenceNameConfig = XmlUtility.DeserializeToObject<EvidenceNameConfig>(message);
                            evidenceCorresponding.EvidenceName(evidenceNameConfig, eivdSourceCode, evidID);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                dataContext.InteractiveShow.LogShow("证据实体对应关系失败" + ex.ToString()); 
            }
           
            #endregion

            #region 1.1执行证据与事实要素对应逻辑
            try
            {
                dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList.ToList());
                if (this.dataContext.DataLayerAns.CaseType.StartsWith("b") || this.dataContext.DataLayerAns.CaseType=="ldzc")
                {
                    #region 没有证据与事实要素的对应配置走固定逻辑
                    //需要比对的基本数据，建立证据与证实内容的关系，并将所有证据获取到放入一个集合；
                    EvidenceDerivationLode();
                    dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList.ToList());
                    locationModel = dataContext.DataLayerSys.locationModelList.FirstOrDefault(a => a.DocType.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());
                    //进行对应关系逻辑比对
                    #region TODO:证据与事实要素关系建立旧逻辑
                   List<RelationShip> relationShips = Correspondence(dataContext.DataLayerAns.CaseCausesList[0].CC_Name, ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("filecreateapi"), dataContext.DataLayerAns.CaseId, dataContext.DataLayerAns.CaseType);
                    #endregion
                    //TODO:ZSW 证据与事实要素关系建立
                    //进行对应关系逻辑比对
                    //List<RelationShip> relationShips = LoadEvidFactRelations();
                    XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
                    dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList.ToList());
                    if (relationShips.Count > 0 && relationShips.FirstOrDefault(a => a.Type == "1") != null)
                    {
                        relationShips = relationShips.Where(a => a.Type == "1").ToList().Distinct().ToList();
                        #region TODO:ZSW 证据与事实要素关系建立旧逻辑
                        //文书生成使用事实要素对应证据关系合并后要素ID调整
                        if (dataContext.DataLayerOpt.FactElementNodeCorredRecords != null && dataContext.DataLayerOpt.FactElementNodeCorredRecords.Any())
                        {
                            //获取文书生成使用事实要素节点比对记录
                            var compRecords = dataContext.DataLayerOpt.FactElementNodeCorredRecords.Where(x => x.ElementType == "8").ToList();
                            if (compRecords != null && compRecords.Any())
                            {
                                foreach (var item in compRecords)
                                {
                                    foreach (var relItem in relationShips.Where(x => x.MergerElementID == item.MergeBeforeId))
                                    {
                                        if (!string.IsNullOrWhiteSpace(item.MergeAfterId))
                                            relItem.MergerElementID = item.MergeAfterId;
                                    }
                                }
                            }
                        }
                        #endregion
                        XmlDocument xmlEvidenc = RelationShipByXML(relationShips);
                        List<DataModel> dataModelEvidenList = xmlUtilCommon.GetXMLByDataModel(xmlEvidenc).dataModelList;
                        if (dataModelEvidenList.Count > 0)
                        {
                            //string docPathNoStage = locationModel.DocPath.Substring(0, locationModel.DocPath.IndexOf("[@阶段"));
                            var evidRootPath = $"{locationModel.DocPath}/证据相关信息";
                            DataModel evidenRelationParentNode = XmlUtility.ConditionFirstOrDefaultDataModel(dataContext.DataLayerOpt.SourdatModleList, "", evidRootPath);
                            //DataModel evidenRelationParentNode = dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.XmlPath == docPathNoStage + @"/证据相关信息");
                            if (evidenRelationParentNode != null)
                            {
                                DataModel Evmodel = dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.ParentId == evidenRelationParentNode.ID);
                                if (Evmodel != null)
                                {
                                    List<DataModel> EvmodelList = dataContext.DataLayerOpt.SourdatModleList.Where(a => a.ParentId == evidenRelationParentNode.ID && a.XmlPath.IndexOf("证据事实要素关系") > -1).ToList();

                                    foreach (var rmodel in EvmodelList)
                                    {
                                        List<DataModel> rmodelList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, rmodel);
                                        foreach (var model in rmodelList)
                                        {
                                            dataContext.DataLayerOpt.SourdatModleList.Remove(model);
                                        }
                                    }
                                }
                                DataSoursModel dataSoursModel = new DataSoursModel();
                                dataSoursModel.dataModelList = dataContext.DataLayerOpt.SourdatModleList;
                                dataModelEvidenList.FirstOrDefault(a => a.ParentId == "").ParentId = evidenRelationParentNode.ID;
                                var relationDetails = dataModelEvidenList.Where(x => x.AttributesList != null && x.AttributesList.Any()).ToList();
                                List<DataModel> resultRelations = new List<DataModel>();

                                foreach (var item in relationDetails)
                                {
                                    var nameId = item.AttributesList.FirstOrDefault(x => x.Name == "证据名称ID")?.sourceList[0]?.SaveValue;
                                    var elementId = item.AttributesList.FirstOrDefault(x => x.Name == "证据要素ID")?.sourceList[0]?.SaveValue;
                                    var factId = item.AttributesList.FirstOrDefault(x => x.Name == "事实要素ID")?.sourceList[0]?.SaveValue;
                                    var sourdataModel = dataContext.DataLayerOpt.SourdatModleList.Where(x => x.XmlPath.Contains(item.XmlPath))
                                                                  .Where(x => x.AttributesList.FirstOrDefault(x => x.Name == "证据名称ID")?.sourceList[0]?.SaveValue == nameId)
                                                                  .Where(x => x.AttributesList.FirstOrDefault(x => x.Name == "证据要素ID")?.sourceList[0]?.SaveValue == elementId)
                                                                  .Where(x => x.AttributesList.FirstOrDefault(x => x.Name == "事实要素ID")?.sourceList[0]?.SaveValue == factId)
                                                                  .ToList();
                                    if (sourdataModel == null || sourdataModel.Count <= 0)
                                    {
                                        resultRelations.Add(item);
                                    }
                                }
                                if (relationDetails != null && relationDetails.Any())
                                {
                                    resultRelations.Insert(0, dataModelEvidenList.FirstOrDefault(a => a.ParentId == evidenRelationParentNode.ID));
                                    dataContext.DataLayerOpt.SourdatModleList.AddRange(resultRelations);
                                }
                                string messagesourmodel = XmlUtility.SerializeToXml<DataSoursModel>(dataSoursModel);
                                XmlDocument SourdataXml = new XmlDocument();
                                SourdataXml.LoadXml(messagesourmodel);
                                XmlDocument xmlDocumentOp = XmlUtility.DataModelByXml(dataSoursModel.dataModelList);
                                dataContext.DataLayerOpt.OptimizationXml = xmlDocumentOp;
                                dataContext.DataLayerOpt.SourdatModleList = dataSoursModel.dataModelList;
                            }
                            ConvertToEviFactElementRelationModel(dataModelEvidenList);
                        }
                    }

                    #endregion
                }
                else
                {
                    #region 有证据与事实对应的配置就走配置 
                    // 读取解析配置信息
                    var detail = config.ConfigDetail.FirstOrDefault(a => a.Code.ToLower() == "evidfactsociety");
                    if (detail != null)
                    {
                        EvidenctFactModel configInfo = new EvidenctFactModel();
                        configInfo = XmlUtility.DeserializeToObject<EvidenctFactModel>(detail.ConfigContent);
                        configInfos.Add(configInfo);
                        FactEvidenc factEvidenc = new FactEvidenc(this.dataContext, configInfo);
                        factEvidenc.Extract();
                    }

                    ConvertToEviFactElementRelationModel(dataContext.DataLayerOpt.SourdatModleList);
                    #endregion
                }
                //证据效力
                //质证意见
            }
            catch (Exception e)
            {
                dataContext.InteractiveShow.LogShow("证据对应关系失败" + e.ToString());
            }
            #endregion

            #region 1.2执行证据效力对要素认定的判断
            EvidentiaryEffectt evidentiaryEffectt = new EvidentiaryEffectt();
            evidentiaryEffectt.AffirmEvidenceState(dataContext.DataLayerOpt.EviFactElementRelations);
            #endregion

            #region 1.3执行质证意见对要素认定的判断
            QuestionElementComparison questionElement = new QuestionElementComparison(dataContext, ModuleName);
            questionElement.ElementComparison();
            #endregion

            dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList.ToList());
            stopwatch.Stop();
            SetModuleProcess(ModuleName + "_" + stopwatch.Elapsed.TotalMilliseconds.ToString("0"), 100, dataContext.InteractiveShow.inputParameterModel);
        }

        /// <summary>
        /// 事实要素与证据要素关系
        /// </summary>
        public void EvidenceDerivationLode()
        {
            DOCLocationModel locationModel = dataContext.DataLayerSys.locationModelList.FirstOrDefault(b => b.DocType.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());//dataLayerStores.docID.ToLower());
            if (locationModel != null)
            {
                string elementpath = locationModel.EelementPaht.Replace("{causecode}",dataContext.DataLayerAns.ExtractCaseCausesList.FirstOrDefault(a=> a.AllParentId.Contains(dataContext.DataLayerAns.CaseCausesList[0].CC_ID)).CC_ID);
                string mergerElmentPath = locationModel.MergeElmentPath.Replace("{causecode}", dataContext.DataLayerAns.ExtractCaseCausesList.FirstOrDefault(a => a.AllParentId.Contains(dataContext.DataLayerAns.CaseCausesList[0].CC_ID)).CC_ID);

                DataModel dataModelElmentRoot = XmlUtility.ConditionFirstOrDefaultDataModel(dataContext.DataLayerOpt.SourdatModleList, "", elementpath);

                MergerElementRoot = XmlUtility.ConditionFirstOrDefaultDataModel(dataContext.DataLayerOpt.SourdatModleList, "", mergerElmentPath);

                XmlUtilCommon xmlUtilCommon = new XmlUtilCommon();
                //进行分组，去重；
                List<DataModel> distinctPeople = dataContext.DataLayerOpt.SourdatModleList.GroupBy(p => p.ID).Select(g => g.First()).ToList();
                dataContext.DataLayerOpt.SourdatModleList = distinctPeople;

                //获取分人员要素
                FactualDataModelList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, dataModelElmentRoot);
                //获取合并后要素
                MergerElementModelList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, MergerElementRoot);

                DataModel eLmentDatamodel = XmlUtility.ConditionFirstOrDefaultDataModel(dataContext.DataLayerOpt.SourdatModleList, "", mergerElmentPath + "/案由要素/事实要素[@要素类型='4']");
                if(eLmentDatamodel!=null)
                {
                    MergerElementModelList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, eLmentDatamodel);
                    MergerElementModelList.Add(dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.ID == eLmentDatamodel.ParentId));
                }
                MergerElementModelList.Add(MergerElementRoot);
                //获取阶段节点
                DataModel dataModelstageRoot = XmlUtility.ConditionFirstOrDefaultDataModel(dataContext.DataLayerOpt.SourdatModleList, "", locationModel.DocPath);
                //获取阶段完整节点
                List<DataModel> dataModelsStagList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, dataModelstageRoot);
                if (dataModelstageRoot != null)
                {
                    List<DataModel> dataModelEvidenList = dataModelsStagList.Where(a => a.XmlPath.IndexOf("证据") > -1 && a.XmlPath.IndexOf("详情") > -1 && a.AttributesList != null && a.AttributesList.FirstOrDefault(b => b.Name == "来源姓名") != null).ToList();
                    foreach (DataModel dataModel in dataModelEvidenList)
                    {
                        if (dataContext.DataLayerAns.IsEvidence == 1)
                        {
                            List<DataModel> dataModelEVList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, dataModel);
                            #region ljx 2022-12-14
                            /**
                             * 经过与白雪峰确认，当回填的结构化数据为证据时，需要在证据详情节点进行判断，根据对应回填的证据code，获取证据集合，根据得到的集合然后进行循环遍历添加对应证据的证实内容。
                             */
                            var dataEvidList = dataModelEVList.Where(a => a.AttributesList.FirstOrDefault(b => b.Name == "证据文书编号") != null
                                                && a.AttributesList.FirstOrDefault(b => b.Name == "证据文书编号").sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());

                            foreach (var dataEvi in dataEvidList)
                            {
                                SqlSysCommon sqlSysCommon = new SqlSysCommon("");
                                string Purpose = sqlSysCommon.GetEvidPurpose(dataContext.DataLayerAns.SourceCode.ToLower());
                                AttributeInfo attributeInfo = new AttributeInfo();
                                attributeInfo.Name = "证实内容";
                                attributeInfo.sourceList = new List<Source>();
                                Source source = new Source();
                                source.SaveValue = Purpose;
                                source.ExtValue = Purpose;
                                source.IsCheck = "1";//加入选中数据
                                source.SourceCode = dataContext.DataLayerAns.SourceCode;
                                attributeInfo.sourceList.Add(source);
                                dataEvi.AttributesList.Add(attributeInfo);
                            }
                            /*--------------------------------------*/
                            //DataModel dataEv = dataModelEVList.FirstOrDefault(a => a.AttributesList.FirstOrDefault(a => a.Name == "证据文书编号") != null);
                            //if (dataEv != null)
                            //{
                            //    string saveValue = dataEv.AttributesList.FirstOrDefault(a => a.Name == "证据文书编号").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                            //    if (!string.IsNullOrEmpty(saveValue))
                            //    {
                            //        SqlSysCommon sqlSysCommon = new SqlSysCommon("");
                            //        string Purpose = sqlSysCommon.GetEvidPurpose(saveValue);
                            //        AttributeInfo attributeInfo = new AttributeInfo();
                            //        attributeInfo.Name = "证实内容";
                            //        attributeInfo.sourceList = new List<Source>();
                            //        Source source = new Source();
                            //        source.SaveValue = Purpose;
                            //        source.ExtValue = Purpose;
                            //        source.IsCheck= "1";//加入选中数据
                            //        attributeInfo.sourceList.Add(source);
                            //        dataEv.AttributesList.Add(attributeInfo);
                            //    }
                            //}
                            #endregion

                        }
                        else
                        {
                            List<DataModel> dataModelEVList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, dataModel);

                            var dataEvidList = dataModelEVList.Where(a => a.AttributesList.FirstOrDefault(b => b.Name == "证据名称") != null
                                                );
                            foreach (var dataEvi in dataEvidList)
                            {
                                SqlSysCommon sqlSysCommon = new SqlSysCommon("");
                                string Purpose = sqlSysCommon.GetEvidPurpose(dataContext.DataLayerAns.SourceCode.ToLower());
                                AttributeInfo attributeInfo = new AttributeInfo();
                                attributeInfo.Name = "证实内容";
                                attributeInfo.sourceList = new List<Source>();
                                Source source = new Source();
                                source.SaveValue = Purpose;
                                source.ExtValue = Purpose;
                                source.IsCheck = "1";//加入选中数据
                                source.SourceCode = dataContext.DataLayerAns.SourceCode;
                                attributeInfo.sourceList.Add(source);
                                dataEvi.AttributesList.Add(attributeInfo);
                            }
                        }
                        EvidenceDataModelList.AddRange(xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, dataModel));
                    }
                }
            }

        }

        /// <summary>
        /// 事实要素与证据的关系
        /// </summary>
        /// <param name="FactualDataModel"></param>
        /// <param name="EvidenceDataModel"></param>
        public EvidenceDerivationClass(List<DataModel> factualDataModel, List<DataModel> evidenceDataModel)
        {
            this.FactualDataModelList = factualDataModel;
            this.EvidenceDataModelList = evidenceDataModel;
        }

        /// <summary>
        /// 对应关系获取
        /// datamodel问题，存在废弃节点没有进行标记，遍历需要多次，浪费；
        /// </summary>
        /// <param name="causeName">案由名称</param>
        public List<RelationShip> Correspondence(string causeName, string evidenceURL, string caseonlyid, string caseType)
        {
            List<RelationShip> dataModelRelationShipList = new List<RelationShip>();
          
            ///证据节点名称
            List<DataModel> dataModelsEvidenRootList = EvidenceDataModelList.Where(a => a.XmlPath.IndexOf("详情") > -1 && a.AttributesList.FirstOrDefault(b => b.Name == "来源姓名") != null).ToList();
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon();
            //不包含证据要素的证据内容
            foreach (DataModel dataEviden in dataModelsEvidenRootList)
            {
                //当前dataEviden指的是证据节点下的详情节点；
                List<DataModel> dataModelList = xmlUtilCommon.SubordinateDataModelList(EvidenceDataModelList, dataEviden);
                //获取证据内容节点Id
                DataModel eviContentNode = dataModelList.FirstOrDefault(x => x.ParentId == dataEviden.ID);
                var eviDetails = dataModelList.Where(x => x.ParentId == eviContentNode?.ID).ToList();

                //获取当前证据详情的主张方姓名
                string name = dataEviden.AttributesList.FirstOrDefault(a => a.Name == "主张方姓名")?.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                int i = 0;
                foreach (var evid in eviDetails)
                {
                    i++;
                    //evid指的是证据内容下的详情节点
                    dataContext.InteractiveShow.LogShow("当前第"+i.ToString()+"个证据");
                    var details = dataModelList.Where(x => x.ParentId == evid?.ID).ToList();
                    if (details.FirstOrDefault(a => a.XmlPath.IndexOf("证据要素") > -1) != null)
                    {
                        #region 同节点对比数据删除
                        //存在证据要素开始对比输出
                        //进行分人员要素的比对
                        List<RelationShip> relationShipList = new List<RelationShip>();
                        relationShipList = ElementComparison(dataModelList, evid, name, "案由要素");
                        relationShipList = relationShipList.Distinct((a, b) => a.EvidenID == b.EvidenID && a.EvidenNameID == b.EvidenNameID && a.XmlPath == b.XmlPath && a.ElmentID == b.ElmentID).ToList();

                        //进行合并后人员要素比对
                        List<RelationShip> relationMergerShipList = new List<RelationShip>();
                        relationMergerShipList = MergerElementComparison(dataModelList, evid, "案由要素");
                        relationMergerShipList = relationMergerShipList.Distinct((a, b) => a.EvidenID == b.EvidenID && a.EvidenNameID == b.EvidenNameID && a.XmlPath == b.XmlPath && a.ElmentID == b.ElmentID).ToList();

                        foreach (RelationShip relation in relationShipList)
                        {
                            RelationShip relationShip = relationMergerShipList.FirstOrDefault(a => a.EvidenID == relation.EvidenID && a.EvidenNameID == relation.EvidenNameID && a.XmlPath == relation.XmlPath);
                            if (relationShip != null)
                            {
                                relationMergerShipList.Remove(relationShip);
                                relation.MergerElementID = relationShip.ElmentID;
                            }
                        }
                        if (relationMergerShipList != null && relationMergerShipList.Count > 0)
                        {
                            foreach (var item in relationMergerShipList)
                            {
                                if (!string.IsNullOrEmpty(item.ElmentID))
                                {
                                    item.MergerElementID = item.ElmentID;
                                    item.ElmentID = "";
                                    dataModelRelationShipList.Add(item);
                                }
                            }
                        }
                        if (relationShipList.Count > 0)
                        {
                            dataModelRelationShipList.AddRange(relationShipList);
                        }
                        #endregion
                    }
                    else
                    {
                        //不存在证据要素
                        DataEvidenceList.Add(evid);
                    }
                }

            }
            //对于不存在证据要素的，证据详情进行关联数据挂接
            if (DataEvidenceList.Count > 0)
            {
                try
                {
                    string url = evidenceURL + "/api/Makedocpdf/GetStandardName";

                    Dictionary<DataModel, List<DataModel>> dicdatamodel = new Dictionary<DataModel, List<DataModel>>();

                    foreach (DataModel model in DataEvidenceList)
                    {
                        DataModel dataModelRoot = EvidenceDataModelList.FirstOrDefault(a => a.ID == model.ParentId);
                        if (dicdatamodel.ContainsKey(dataModelRoot))
                        {

                            dicdatamodel[dataModelRoot].Add(model);
                        }
                        else
                        {
                            List<DataModel> datalist = new List<DataModel>();
                            datalist.Add(model);
                            dicdatamodel.Add(dataModelRoot, datalist);
                        }

                    }
                    foreach (var itemdata in dicdatamodel)
                    {
                        int i = 0;
                        foreach (DataModel model in itemdata.Value)
                        {
                            i++;
                            dataContext.InteractiveShow.LogShow("当前第" + i.ToString() + "个数据");
                            if (model.AttributesList.FirstOrDefault(a => a.Name == "证据名称") != null)
                            {
                                List<string> evidenName = new List<string>();
                                evidenName.Add(model.AttributesList.FirstOrDefault(a => a.Name == "证据名称").sourceList.FirstOrDefault(b => b.IsCheck == "1").SaveValue);
                                LdtJudge.DataEngine.Model.CommModel.EvidenceModel evidenceModel = new LdtJudge.DataEngine.Model.CommModel.EvidenceModel();
                                evidenceModel.CaseID = caseonlyid;
                                evidenceModel.CaseType = caseType;
                                evidenceModel.DocNames = evidenName;
                                var evidenDetail = EvidenceDataModelList.FirstOrDefault(a => a.ID == itemdata.Key.ParentId && a.AttributesList.FirstOrDefault(b => b.Name == "主张方姓名") != null);
                                string name = evidenDetail?.AttributesList.FirstOrDefault(a => a.Name == "主张方姓名")?.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                List<DataModel> dataModelElementRoot = FactualDataModelList.Where(a => a.XmlPath.IndexOf("主张方") > -1 &&
                                a.AttributesList.FirstOrDefault(b => b.Name == "主张方姓名或名称").sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == name).ToList();
                                foreach (DataModel dataModelElement in dataModelElementRoot.Where(a => a.XmlPath.IndexOf("事实要素") > -1))
                                {
                                    //得到事实根节点
                                    DataModel factualRoot = FactualDataModelList.FirstOrDefault(a => a.ID == dataModelElement.ParentId);
                                    DataModel rootNode = FactualDataModelList.FirstOrDefault(x => x.ID == factualRoot.ParentId);

                                    //事实要素集合
                                    List<DataModel> factualList = xmlUtilCommon.SubordinateDataModelList(FactualDataModelList, factualRoot);
                                    factualList.Insert(0, rootNode);
                                    EvidentialElementsXML(evidenceModel, url, factualList,dataModelRelationShipList, itemdata.Key.ID, model);
     
                                }
                            }
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    dataContext.InteractiveShow.LogShow("证据与事实关系对应错误！！" + ex.ToString());
                }
            }
            //}

            return dataModelRelationShipList.Distinct().ToList();
        }

        /// <summary>
        /// 上层如果传入证据与事实关系路径集合
        /// 执行证据与事实要素关系对应
        /// </summary>
        private List<RelationShip> EvidenceRelFactXpathList()
        {
            List<RelationShip> relationList = new List<RelationShip>();

            try
            {
                XmlUtilCommon xmlUtilCommon = new XmlUtilCommon();

                //1、解析上层应用传入的证据关键路径

                List<Tuple<string, string>> XpathListContent = new List<Tuple<string, string>>();
                string xpathContent = dataContext.DataLayerAns.EvidenceXpathList;
                xpathContent = HttpHelp.DeCodeBase64new(65001, xpathContent.Replace('"', ' ')).Replace("&lt;", "<").Replace("&gt;", ">");
                XmlDocument document = new XmlDocument();
                document.LoadXml(xpathContent);

                //2、进行关键路径拆分

                XmlNodeList nodeList = document.SelectNodes("/root/xpath");
                string evidPath = "";
                foreach (XmlNode item in nodeList)
                {
                    if (!string.IsNullOrWhiteSpace(item.InnerText))
                    {
                        evidPath = item.InnerText.Substring(0, item.InnerText.IndexOf("/证据内容"));
                        string path = item.InnerText.Substring(item.InnerText.IndexOf("/案由要素"));
                        XpathListContent.Add(new Tuple<string, string>(path, item.InnerText));
                    }
                }
                XmlDocument optxml = dataContext.DataLayerOpt.OptimizationXml;
                XmlNode evidNode = optxml.SelectSingleNode(evidPath);

                //2.1、拆分为分人员及合并后;
                string zhuzhangName = evidNode.Attributes["主张方姓名"]?.Value;
                //获取到分人员事实要素与当前证据主张人员对应的数据
                List<DataModel> dataModelElementRoot = FactualDataModelList.Where(a => a.XmlPath.IndexOf("主张方") > -1 &&
                a.AttributesList.FirstOrDefault(b => b.Name == "主张方姓名或名称").sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == zhuzhangName && a.XmlPath.IndexOf("事实要素") > -1).ToList();
                //获取分人员的事实要素与证据要素的关系；
                var fenrenyuanFact = FactualDataModelList.FirstOrDefault(a => a.ID == dataModelElementRoot[0].ParentId);
                //得到事实根节点
                DataModel factualRoot = FactualDataModelList.FirstOrDefault(a => a.ID == fenrenyuanFact.ParentId);
                //事实要素集合
                List<DataModel> factualList = xmlUtilCommon.SubordinateDataModelList(FactualDataModelList, factualRoot);
                foreach (var (path, orgpath) in XpathListContent)
                {
                    //找到符合当前xpath的事实要素节点；
                    //List<DataModel> factmodellist= XmlUtility.ConditionDataModelList(factualList, factualRoot.ParentId, path);
                    var relation = CreateRelations(factualList, factualRoot.ParentId, path, orgpath);

                    //3、进行路径与事实要素关系挂接；
                    //获取合并后事实要素与证据要素的关系；
                    var mergerelation = CreateRelations(MergerElementModelList, MergerElementRoot.ID, path, orgpath, true);
                    if (relation != null && mergerelation != null)
                    {
                        relation.MergerElementID = mergerelation.MergerElementID;
                    }

                    if (relation != null)
                    {
                        relationList.Add(relation);
                    }
                    else if (mergerelation != null)
                    {
                        relationList.Add(mergerelation);
                    }
                }
            }
            catch (Exception exc)
            {
                dataContext.InteractiveShow.LogShow("证据与事实关键路径关系对应错误！！" + exc.Message, LogMessageType.Error);
                dataContext.InteractiveShow.LogShow(exc.StackTrace, LogMessageType.Error);
            }
            return relationList;
        }

        /// <summary>
        /// 获取证据要素与事实要素的关系数据
        /// </summary>
        /// <param name="dataModelList"></param>
        /// <param name="parentid"></param>
        /// <param name="xmlpath"></param>
        /// <param name="orgpath"></param>
        /// <param name="isMerge">是否为合并后要素</param>
        /// <returns></returns>
        private RelationShip CreateRelations(List<DataModel> dataModelList, string parentid, string xmlpath, string orgpath, bool isMerge = false)
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon();
            XmlDocument xmlDocument = xmlUtilCommon.DataModelByXml(dataModelList, parentid, false);

            XmlNode fenrenyuanxmlNode = xmlDocument.SelectSingleNode(xmlpath);

            XmlDocument optResultXml = dataContext.DataLayerOpt.OptimizationXml;

            XmlNode optResultNode = optResultXml.SelectSingleNode(orgpath);

            string parent_path = orgpath.Substring(0, orgpath.Length - xmlpath.Length);
            XmlNode parentNode = optResultXml.SelectSingleNode(parent_path);
            string eviid = parentNode.ParentNode.Attributes["id"].Value.ToString();
            List<DataModel> resultList = new List<DataModel>();
            if (fenrenyuanxmlNode != null && optResultNode != null)
            {
                if (optResultNode.NodeType == XmlNodeType.Attribute)
                {
                    RelationShip relationShipzt = new RelationShip();
                    relationShipzt.EvidenID = (optResultNode as XmlAttribute).OwnerElement.Attributes["id"].Value;
                    relationShipzt.EvidenNameID = eviid;
                    relationShipzt.XmlPath = xmlpath.TrimStart('/');
                    if (isMerge)
                    {
                        relationShipzt.MergerElementID = (fenrenyuanxmlNode as XmlAttribute).OwnerElement.Attributes["id"].Value;
                    }
                    else
                    {
                        relationShipzt.ElmentID = (fenrenyuanxmlNode as XmlAttribute).OwnerElement.Attributes["id"].Value;
                    }
                    if (optResultNode.Value.Equals(fenrenyuanxmlNode.Value))
                    {
                        relationShipzt.Type = "1";
                    }
                    else
                    {
                        relationShipzt.Type = "2";
                    }
                    return relationShipzt;
                }
            }
            return null;
        }

        /// <summary>
        /// 进行证据与事实要素的关系重新挂接
        /// </summary>
        /// <param name="OpdataSoursModel">优选后的数据模型</param>
        /// <param name="FenRenyuandataMode">分人员要素集合</param>
        /// <param name="MergedataModelList">合并后要素集合</param>
        private void ReUpdateRelations(List<DataModel> OpdataSoursModel, List<DataModel> FenRenyuandataMode, List<DataModel> MergedataModelList)
        {
            foreach (var eviditem in OpdataSoursModel)
            {
                string xmlpath = eviditem.AttributesList.FirstOrDefault(a => a.Name == "xpath路径")?.sourceList.FirstOrDefault(b => b.AnalysisStatus != "2").SaveValue;
                string evid = eviditem.AttributesList.FirstOrDefault(a => a.Name == "证据名称ID")?.sourceList.FirstOrDefault(b => b.AnalysisStatus != "2").SaveValue;
                if (string.IsNullOrWhiteSpace(xmlpath) || string.IsNullOrWhiteSpace(evid))
                {
                    continue;
                }
                //证据内容ID
                string evconid = OpdataSoursModel.FirstOrDefault(a => a.ID == evid)?.ParentId;
                //证据/详情id
                string xiangqingid = OpdataSoursModel.FirstOrDefault(a => a.ID == evconid)?.ParentId;
                string xingming = OpdataSoursModel.FirstOrDefault(a => a.ID == xiangqingid)?.AttributesList.FirstOrDefault(b => b.Name == "主张方姓名")?.sourceList.FirstOrDefault(b => b.AnalysisStatus != "2").SaveValue;

                XmlUtilCommon xmlUtilCommon = new XmlUtilCommon();
                //1、进行分人员的关系重新挂接；
                //1.1、根据证据ID，获取证据的主张方名称
                string zhuzhangName = xingming;
                //1.2、根据主张方名称，或者对应的分人员事实要素；

                //获取到分人员事实要素与当前证据主张人员对应的数据
                List<DataModel> dataModelElementRoot = FenRenyuandataMode.Where(a => a.XmlPath.IndexOf("主张方") > -1 &&
                a.AttributesList.FirstOrDefault(b => b.Name == "主张方姓名或名称").sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == zhuzhangName && a.XmlPath.IndexOf("事实要素") > -1).ToList();
                //获取分人员的事实要素与证据要素的关系；
                var fenrenyuanFact = FenRenyuandataMode.FirstOrDefault(a => a.ID == dataModelElementRoot[0].ParentId);
                //得到事实根节点
                DataModel factualRoot = FenRenyuandataMode.FirstOrDefault(a => a.ID == fenrenyuanFact.ParentId);
                //事实要素集合
                List<DataModel> factualList = xmlUtilCommon.SubordinateDataModelList(FactualDataModelList, factualRoot);

                XmlDocument FenrenyuanXDocument = xmlUtilCommon.DataModelByXml(factualList, factualRoot.ParentId, false);
                XmlNode fenrenyuanxmlNode = FenrenyuanXDocument.SelectSingleNode(xmlpath);
                if (fenrenyuanxmlNode != null)
                {
                    string id = fenrenyuanxmlNode.Attributes["id"].Value;
                    //eviditem.AttributesList.FirstOrDefault(a => a.Name == "证据要素ID")?.sourceList.FirstOrDefault(b => b.AnalysisStatus != "2").SaveValue;
                }

                //2、进行合并后人员要素的关系重新挂接；
                XmlDocument HebingYaoSuXDocument = xmlUtilCommon.DataModelByXml(MergedataModelList, MergerElementRoot.ID, false);
                if (HebingYaoSuXDocument != null)
                {
                    string id = HebingYaoSuXDocument.Attributes["id"].Value;
                    //eviditem.AttributesList.FirstOrDefault(a => a.Name == "合并后要素ID")?.sourceList.FirstOrDefault(b => b.AnalysisStatus != "2").SaveValue;
                }
            }

        }

        /// <summary>
        /// xml转数据对象集合
        /// </summary>
        /// <param name="xmlStr"></param>
        /// <returns></returns>
        private List<DOCLocationModel> GetLocationModels(string causeLocalXml, string causeStageXml)
        {
            List<CTLocationModel> cTLocations = new List<CTLocationModel>();
            ParseLocationConfig locationConfigM = new ParseLocationConfig();
            var locationModels = locationConfigM.GetLocationModel(causeLocalXml, causeStageXml, dataContext.DataLayerOpt.OptimizationXml, dataContext.DataLayerAns.CaseType, dataContext.DataLayerAns.SourceCode);
            return locationModels;
        }
        /// <summary>
        /// 将对比数据更新为XML
        /// </summary>
        /// <param name="dataModelRelationShipList">xml</param>
        /// <returns></returns>
        public XmlDocument RelationShipByXML(List<RelationShip> dataModelRelationShipList)
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlElement rootElement = xmlDocument.CreateElement("证据事实要素关系");
            RelationByNode(rootElement, dataModelRelationShipList, xmlDocument);
            xmlDocument.AppendChild(rootElement);
            return xmlDocument;
        }
        /// <summary>
        /// 结果实体解析为node
        /// </summary>
        /// <param name="xmlElementPranet">上级节点</param>
        /// <param name="dataModelRelationShipList">结果实体</param>
        /// <param name="xmlDocument">xml要素</param>
        public void RelationByNode(XmlElement xmlElementPranet, List<RelationShip> dataModelRelationShipList, XmlDocument xmlDocument)
        {
            foreach (RelationShip relationShip in dataModelRelationShipList)
            {
                XmlElement xmlElementNodel = xmlDocument.CreateElement("详情");
                xmlElementNodel.SetAttribute("证据名称ID", relationShip.EvidenNameID);
                xmlElementNodel.SetAttribute("证据要素ID", relationShip.EvidenID);
                xmlElementNodel.SetAttribute("事实要素ID", relationShip.ElmentID);
                xmlElementNodel.SetAttribute("要素分类", relationShip.ElementType);
                xmlElementNodel.SetAttribute("xpath路径", relationShip.XmlPath);
                xmlElementNodel.SetAttribute("合并后要素ID", relationShip.MergerElementID);
                xmlElementNodel.SetAttribute("关系类型", "2");
                xmlElementPranet.AppendChild(xmlElementNodel);
            }
        }

        #region 要素对比
        /// <summary>
        /// 进行要素对比
        /// </summary>
        /// <param name="dataEvidenList">当前证据详情集合</param>
        /// <param name="currentEvid">当前证据</param>
        /// <param name="causeName">案由名称</param>
        public List<RelationShip> ElementComparison(List<DataModel> dataEvidenList, DataModel currentEvid, string zhuzhangname, string causeName)
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon();
            List<RelationShip> dataModelResultList = new List<RelationShip>();
            List<DataModel> dataModelElementRoot = FactualDataModelList.Where(a => a.XmlPath.IndexOf("主张方") > -1 &&
            a.AttributesList.FirstOrDefault(b => b.Name == "主张方姓名或名称").sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == zhuzhangname).ToList();
            foreach (DataModel dataModelElement in dataModelElementRoot.Where(a => a.XmlPath.IndexOf("事实要素") > -1))
            {
                List<DataModel> dataModelEvidensList = xmlUtilCommon.SubordinateDataModelList(dataEvidenList, currentEvid);
                //这里先进行正反序列化处理，原因是，由于对象应用，把证据要素重复添加，原因是在下面的补充xpath方法中，把原来的xpath修改，导致后面重复添加；
                string damsg = JsonConvert.SerializeObject(dataModelEvidensList);
                List<DataModel> dataModelEvidensRulesList = JsonConvert.DeserializeObject<List<DataModel>>(damsg);
                if (dataModelEvidensRulesList != null && dataModelEvidensRulesList.Count > 1)
                {
                    try
                    {
                        //去空节点
                        dataModelEvidensRulesList = xmlUtilCommon.EmptyNode(dataModelEvidensRulesList, currentEvid, true);
                        //得到事实根节点
                        DataModel factualRoot = FactualDataModelList.FirstOrDefault(a => a.ID == dataModelElement.ParentId);
                        //事实要素集合
                        List<DataModel> factualList = xmlUtilCommon.SubordinateDataModelList(FactualDataModelList, factualRoot);
                        string xmlpath = "";
                        if (dataContext.DataLayerAns.CaseCausesList.Count > 0)
                        {
                            xmlpath = BllDataHandle.GetCurrentProgramPath() + @"\Config\FactOptimizeConfig\CommonFact\b1\" + dataContext.DataLayerAns.CaseCausesList[0].CC_ID + ".xml";
                        }
                        if (!string.IsNullOrEmpty(IsXpath))
                        {
                            xmlpath = BllDataHandle.GetCurrentProgramPath() + @"\bin\Config\FactOptimizeConfig\CommonFact\b1\" + dataContext.DataLayerAns.CaseCausesList[0].CC_ID + ".xml";
                        }
                        //查询事实要素的提取合并配置（用证据代替）
                        OptimizeSourceSerializable optimizeSource = new OptimizeSourceSerializable();
                        LdtJudge.DataEngine.Model.XMLConfigModel.OptimizeConfigModel.OptimizeFactConfig optimizeFact = new LdtJudge.DataEngine.Model.XMLConfigModel.OptimizeConfigModel.OptimizeFactConfig();
                        // 从上下文获取配置信息，如果上下文中没有对应的配置重新拉取配置
                        if (dataContext.DataLayerSys.optimizeFactConfig != null)
                        {
                            optimizeFact = dataContext.DataLayerSys.optimizeFactConfig;
                        }
                        else
                        {
                            optimizeFact = optimizeSource.OptimizeCommonSource(xmlpath);
                            dataContext.DataLayerSys.optimizeFactConfig = optimizeFact;
                        }
                        //获取相同节点配置
                        var sameNodeConfig = GetSameNodeConfig();
                        List<SameNodeXml> opconfigList = sameNodeConfig?.xmllable?.ToList();

                        //标准化xpath，前面加“/”
                        for (int i = 0; i < dataModelEvidensRulesList.Count; i++)
                        {
                            if (dataModelEvidensRulesList[i].XmlPath.Substring(0, 1) != @"/")
                            {
                                dataModelEvidensRulesList[i].XmlPath = "/" + dataModelEvidensRulesList[i].XmlPath;
                            }
                        }

                        DataModel evidenElementRoot = dataModelEvidensRulesList.FirstOrDefault(a => a.XmlPath == @"/证据要素");
                        if (evidenElementRoot == null)
                        {
                            evidenElementRoot = dataModelEvidensRulesList.FirstOrDefault(a => a.XmlPath == @"/详情/证据内容/详情/证据要素");
                        }
                        if (evidenElementRoot == null)
                        {
                            evidenElementRoot = dataModelEvidensRulesList.FirstOrDefault(a => a.XmlPath.Split('/')[a.XmlPath.Split('/').Length - 1] == "证据要素");
                        }
                        if (evidenElementRoot != null)
                        {
                            List<DataModel> evidenElmentList = xmlUtilCommon.SubordinateDataModelList(dataModelEvidensRulesList, evidenElementRoot);
                            #region 该遍历方法存在问题，把元数据的xpath修改了
                            foreach (DataModel evidenModel in evidenElmentList)
                            {
                                if (evidenModel.XmlPath != @"/证据要素" && evidenModel.XmlPath.IndexOf(causeName) == -1 && evidenModel.XmlPath != @"/详情/证据内容/详情/证据要素" && evidenModel.XmlPath != @"/证据详情/证据内容详情/证据要素" &&
                                    evidenModel.XmlPath.Split('/')[evidenModel.XmlPath.Split('/').Length - 1] != "证据要素")
                                {
                                    if (evidenModel.XmlPath.IndexOf("/" + causeName) == -1)
                                    {
                                        if (evidenModel.XmlPath.IndexOf("/证据要素") > -1)
                                        {
                                            evidenModel.XmlPath = evidenModel.XmlPath.Replace("/证据要素", "");
                                        }
                                        evidenModel.XmlPath = "/" + causeName + evidenModel.XmlPath;
                                    }
                                }
                                else if (evidenModel.XmlPath.IndexOf("证据要素") > -1)
                                {
                                    var xapthitems = evidenModel.XmlPath.Split(new string[] { "证据要素" }, System.StringSplitOptions.None);
                                    evidenModel.XmlPath = xapthitems[xapthitems.Length - 1];
                                    if (evidenModel.XmlPath == "/" || string.IsNullOrEmpty(evidenModel.XmlPath))
                                    {
                                        evidenModel.XmlPath = "/证据要素";
                                    }
                                    else if (evidenModel.XmlPath != @"/证据要素" && evidenModel.XmlPath.IndexOf(causeName) == -1 && evidenModel.XmlPath != @"/详情/证据内容/详情/证据要素" && evidenModel.XmlPath != @"/证据详情/证据内容详情/证据要素")
                                    {
                                        evidenModel.XmlPath = "/" + causeName + evidenModel.XmlPath;
                                    }
                                }

                            }
                            #endregion

                            MultFactUnionDataModel multFactUnionData = new MultFactUnionDataModel();
                            XmlDocument xmldoc = xmlUtilCommon.DataModelByXml(factualList, factualRoot.ParentId);
                            List<RelationShip> dataModelResuList = new List<RelationShip>();
                            multFactUnionData.MultiFactUnionNode(dataModelEvidensRulesList, currentEvid.ID, factualList, factualRoot.ID, opconfigList, dataModelResuList, "b");
                            foreach (RelationShip relation in dataModelResuList)
                            {
                                relation.EvidenNameID = currentEvid.ID;
                                relation.ElementType = "1";
                            }
                            dataModelResultList.AddRange(dataModelResuList);
                        }
                        else
                        {
                            DataEvidenceList.Add(currentEvid);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        dataContext.InteractiveShow.LogShow("证据要素对比失败！" + ex.ToString());
                    }
                }
            }
            return dataModelResultList;
        }

        /// <summary>
        /// 合并后要素进行数据对比
        /// </summary>
        /// <param name="dataEvidenList"></param>
        /// <param name="currentEvid">当前证据信息</param>
        /// <param name="causeName"></param>
        /// <returns></returns>
        public List<RelationShip> MergerElementComparison(List<DataModel> dataEvidenList, DataModel currentEvid, string causeName)
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon();
            List<RelationShip> dataModelResultList = new List<RelationShip>();
            List<DataModel> dataModelEvidensList = xmlUtilCommon.SubordinateDataModelList(dataEvidenList, currentEvid);

            //这里先进行正反序列化处理，原因是，由于对象应用，把证据要素重复添加，原因是在下面的补充xpath方法中，把原来的xpath修改，导致后面重复添加；
            string damsg = JsonConvert.SerializeObject(dataModelEvidensList);
            List<DataModel> dataModelEvidensRulesList = JsonConvert.DeserializeObject<List<DataModel>>(damsg);
            if (dataModelEvidensRulesList != null && dataModelEvidensRulesList.Count > 1)
            {
                dataModelEvidensRulesList = xmlUtilCommon.EmptyNode(dataModelEvidensRulesList, currentEvid, true);
                for (int i = 0; i < dataModelEvidensRulesList.Count; i++)
                {
                    if (dataModelEvidensRulesList[i].XmlPath.Substring(0, 1) != @"/")
                    {
                        dataModelEvidensRulesList[i].XmlPath = "/" + dataModelEvidensRulesList[i].XmlPath;
                    }
                }

                DataModel evidenElementRoot = dataModelEvidensRulesList.FirstOrDefault(a => a.XmlPath == @"/证据要素");
                if (evidenElementRoot == null)
                {
                    evidenElementRoot = dataModelEvidensRulesList.FirstOrDefault(a => a.XmlPath == @"/详情/证据内容/详情/证据要素");
                }
                if (evidenElementRoot == null)
                {
                    evidenElementRoot = dataModelEvidensRulesList.FirstOrDefault(a => a.XmlPath.Split('/')[a.XmlPath.Split('/').Length - 1] == "证据要素");
                }
                if (evidenElementRoot != null)
                {
                    List<DataModel> evidenElmentList = xmlUtilCommon.SubordinateDataModelList(dataModelEvidensRulesList, evidenElementRoot);
                    #region 该遍历方法存在问题，把元数据的xpath修改了
                    foreach (DataModel evidenModel in evidenElmentList)
                    {
                        if (evidenModel.XmlPath != @"/证据要素" && evidenModel.XmlPath.IndexOf(causeName) == -1 && evidenModel.XmlPath != @"/详情/证据内容/详情/证据要素" && evidenModel.XmlPath != @"/证据详情/证据内容详情/证据要素" &&
                            evidenModel.XmlPath.Split('/')[evidenModel.XmlPath.Split('/').Length - 1] != "证据要素")
                        {
                            if (evidenModel.XmlPath.IndexOf("/" + causeName) == -1)
                            {
                                if (evidenModel.XmlPath.IndexOf("/证据要素") > -1)
                                {
                                    evidenModel.XmlPath = evidenModel.XmlPath.Replace("/证据要素", "");
                                }
                                evidenModel.XmlPath = "/" + causeName + evidenModel.XmlPath;
                            }
                        }
                        else if (evidenModel.XmlPath.IndexOf("证据要素") > -1)
                        {
                            var xapthitems = evidenModel.XmlPath.Split(new string[] { "证据要素" }, System.StringSplitOptions.None);
                            evidenModel.XmlPath = xapthitems[xapthitems.Length - 1];
                            if (evidenModel.XmlPath == "/" || string.IsNullOrEmpty(evidenModel.XmlPath))
                            {
                                evidenModel.XmlPath = "/证据要素";
                            }
                            else if (evidenModel.XmlPath != @"/证据要素" && evidenModel.XmlPath.IndexOf(causeName) == -1 && evidenModel.XmlPath != @"/详情/证据内容/详情/证据要素" && evidenModel.XmlPath != @"/证据详情/证据内容详情/证据要素")
                            {
                                evidenModel.XmlPath = "/" + causeName + evidenModel.XmlPath;
                            }
                        }
                    }
                    #endregion
                }
                var sameNodeConfig = GetSameNodeConfig();
                List<SameNodeXml> opconfigList = sameNodeConfig?.xmllable?.ToList();
                MultFactUnionDataModel multFactUnionData = new MultFactUnionDataModel();
                List<RelationShip> dataModelResuList = new List<RelationShip>();
                multFactUnionData.MultiFactUnionNode(dataModelEvidensRulesList, currentEvid.ID, MergerElementModelList, MergerElementRoot.ID, opconfigList, dataModelResuList, "b");
                foreach (RelationShip relation in dataModelResuList)
                {
                    relation.EvidenNameID = currentEvid.ID;
                    relation.ElementType = "1";
                }
                dataModelResultList.AddRange(dataModelResuList);
            }
            return dataModelResultList;
        }
        /// <summary>
        /// 执行无证据要素对比
        /// </summary>
        /// <param name="evidenceModel">证据查询实体</param>
        /// <param name="url">证据查询地址</param>
        public void EvidentialElementsXML(LdtJudge.DataEngine.Model.CommModel.EvidenceModel evidenceModel, string url, List<DataModel> factMoldeList, List<RelationShip> dataModelResultList,string id,DataModel elmentID)
        {
            SqlSysCommon sqlSysCommon = new SqlSysCommon("");
            string jsonstr = JsonConvert.SerializeObject(evidenceModel);
            
            string message = HttpHelp.CreatePostHttpResponse(url, jsonstr);
            bool fal = false;
            LdtJudge.DataEngine.Model.CommModel.ResultModel resultModel = JsonConvert.DeserializeObject<LdtJudge.DataEngine.Model.CommModel.ResultModel>(message);
            var rootNode = factMoldeList[0];
            //foreach (var itemDic in resultModel.body.DocNameDict)
            //{
            //    if (itemDic.Value.Count==0)
            //    {
            //        fal = true;
            //    }
            //    foreach (DicModel dicModel in itemDic.Value)
            //    {
            //        string fl_id = dicModel.Item1;
            //        string ct_code = dicModel.Item3;
            //        List<SYS_CaseType_DocType> dataTable = sqlSysCommon.Getsys_CaseType_DocType(ct_code);
            //        if (dataTable.Count > 0)
            //        {
            //            string cd_id = dataTable[0].CD_ID;
            //            List<SYS_CaseCauseElement_EvidRel> datact = sqlSysCommon.GetSYS_CaseCauseElement_EvidRel(cd_id, dataContext.DataLayerAns.CaseCausesList[0].CC_ID);
            //            if (dataTable.Count > 0)
            //            {
            //                foreach (var itemdatact in datact)
            //                {
            //                    string xpath = itemdatact.XmlPath.ToString();
            //                    DataModel dataModelfact = XmlUtility.ConditionFirstOrDefaultDataModel(factMoldeList, rootNode.ParentId, xpath);
            //                    if (elmentID != null)
            //                    {
            //                        if (elmentID.AttributesList.FirstOrDefault(a => a.Name == "标准名称") == null)
            //                        {
            //                            dataContext.InteractiveShow.LogShow("调用证据名称标准化接口参数：" + jsonstr + "返回结果：" + message);
            //                            AttributeInfo attributeInfo = new AttributeInfo();
            //                            attributeInfo.Name = "标准名称";
            //                            attributeInfo.sourceList = new List<Source>();
            //                            Source source = new Source();
            //                            source.SaveValue = dataTable[0].CD_Name;
            //                            source.ExtValue = dataTable[0].CD_Name;
            //                            source.IsCheck = "1";//加入选中数据
            //                            attributeInfo.sourceList.Add(source);
            //                            elmentID.AttributesList.Add(attributeInfo);
            //                        }

            //                        if (elmentID.AttributesList.FirstOrDefault(a => a.Name == "证据文书编号") == null)
            //                        {
            //                            AttributeInfo attributeInfocode = new AttributeInfo();
            //                            attributeInfocode.Name = "证据文书编号";
            //                            attributeInfocode.sourceList = new List<Source>();
            //                            Source sourcecode = new Source();
            //                            sourcecode.SaveValue = ct_code;
            //                            sourcecode.ExtValue = ct_code;
            //                            sourcecode.IsCheck = "1";//加入选中数据
            //                            attributeInfocode.sourceList.Add(sourcecode);
            //                            elmentID.AttributesList.Add(attributeInfocode);
            //                        }


            //                        RelationShip relationShip = new RelationShip();
            //                        relationShip.EvidenID = id;
            //                        relationShip.ElmentID = dataModelfact?.ID;
            //                        relationShip.EvidenNameID = elmentID.ID;
            //                        relationShip.XmlPath = itemdatact.XmlPath.ToString();
            //                        relationShip.Type = "1";
            //                        relationShip.ElementType = "1";
            //                        dataModelResultList.Add(relationShip);
            //                    }

            //                }
            //            }
            //        }

            //        return;
            //    }
            //}

            if (true)
            {
                Dictionary<string, string> dicElement = new Dictionary<string, string>();
                dicElement.Add("name", evidenceModel.DocNames[0]);
                dicElement.Add("caseid", dataContext.DataLayerAns.CaseId);
                string urls = ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("filemanage") + "/v5/Dossier/GetStandName";
                string value = WebUtil.DoGet(urls, dicElement, "utf-8");
                dataContext.InteractiveShow.LogShow("李圳识别接口返回数据：" + value + "参数：" + JsonConvert.SerializeObject(dicElement)+"路径："+url);
                ResultEvideMdoel resultEvideMdoel= JsonConvert.DeserializeObject<ResultEvideMdoel>(value);

                if (resultEvideMdoel.result.Code=="1")
                {
                    if (resultEvideMdoel.body.body!=null)
                    {
                        if (resultEvideMdoel.body.body.collects!=null && resultEvideMdoel.body.body.collects.Count>0)
                        {
                            string evidname = resultEvideMdoel.body.body.collects[0].Collect_name;
                            string ct_code = resultEvideMdoel.body.body.collects[0].Collect_type;
                            if (!string.IsNullOrEmpty(ct_code))
                            {
                                List<SYS_CaseType_DocType> dataTable = sqlSysCommon.Getsys_CaseType_DocType(ct_code);
                                if (dataTable.Count > 0)
                                {
                                    string cd_id = dataTable[0].CD_ID;
                                    if (elmentID!=null)
                                    {
                                        if (elmentID.AttributesList.FirstOrDefault(a => a.Name == "标准名称") == null)
                                        {
                                            dataContext.InteractiveShow.LogShow("调用证据名称标准化接口参数：" + jsonstr + "返回结果：" + message);
                                            AttributeInfo attributeInfo = new AttributeInfo();
                                            attributeInfo.Name = "标准名称";
                                            attributeInfo.sourceList = new List<Source>();
                                            Source source = new Source();
                                            source.SaveValue = dataTable[0].CD_Name;
                                            source.ExtValue = dataTable[0].CD_Name;
                                            source.IsCheck = "1";//加入选中数据
                                            attributeInfo.sourceList.Add(source);
                                            elmentID.AttributesList.Add(attributeInfo);
                                        }

                                        if (elmentID.AttributesList.FirstOrDefault(a => a.Name == "证据文书编号") == null)
                                        {
                                            AttributeInfo attributeInfocode = new AttributeInfo();
                                            attributeInfocode.Name = "证据文书编号";
                                            attributeInfocode.sourceList = new List<Source>();
                                            Source sourcecode = new Source();
                                            sourcecode.SaveValue = ct_code;
                                            sourcecode.ExtValue = ct_code;
                                            sourcecode.IsCheck = "1";//加入选中数据
                                            attributeInfocode.sourceList.Add(sourcecode);
                                            elmentID.AttributesList.Add(attributeInfocode);
                                        }
                                    }
                                    List<SYS_CaseCauseElement_EvidRel> datact = sqlSysCommon.GetSYS_CaseCauseElement_EvidRel(cd_id,dataContext.DataLayerAns.CaseCausesList[0].CC_ID);
                                    if (dataTable.Count > 0)
                                    {
                                        foreach (var itemdatact in datact)
                                        {
                                            string xpath = itemdatact.XmlPath.ToString();
                                            DataModel dataModelfact = XmlUtility.ConditionFirstOrDefaultDataModel(factMoldeList, rootNode.ParentId, xpath);
                                            if (elmentID != null)
                                            {
                                              


                                                RelationShip relationShip = new RelationShip();
                                                relationShip.EvidenID = id;
                                                relationShip.ElmentID = dataModelfact?.ID;
                                                relationShip.EvidenNameID = elmentID.ID;
                                                relationShip.XmlPath = itemdatact.XmlPath.ToString();
                                                relationShip.Type = "1";
                                                relationShip.ElementType = "1";
                                                dataModelResultList.Add(relationShip);
                                            }

                                        }
                                    }
                                }
                            }
                            
                        }
                    }
                }
            }
        }

        private SameNodeConfig GetSameNodeConfig()
        {
            var configModel = dataContext.DataLayerSys.GetConfigModel(ModuleName);
            SameNodeConfig sameNodeConfig = new SameNodeConfig();
            if (dataContext.DataLayerAns.CaseCausesList.Count > 0)
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(configModel.ConfigContent);
                XmlNode xmlNode = xmlDocument.SelectSingleNode("/root/step[@code='samenodejudge']");
                if (xmlNode != null)
                {
                    Dictionary<string, string> dicElement = new Dictionary<string, string>();
                    string url = xmlNode.Attributes["executefile"].Value;
                    url = url.Replace("{casetype}", dataContext.DataLayerAns.CaseType).Replace("{causecode}", dataContext.DataLayerAns.CaseCausesList[0].CC_ID);
                    dicElement.Add("fileFullName", url);
                    string elementMessage = WebUtil.DoGet(ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("systemapi") + "/api/WordParse/GetConfigFileContent", dicElement, "utf-8");
                    dynamic elementcofig = JsonConvert.DeserializeObject<dynamic>(elementMessage);
                    if (elementcofig.result.code.ToString() == "1")
                    {
                        string elementcofigstr = elementcofig.body;
                        sameNodeConfig = XmlUtility.DeserializeToObject<SameNodeConfig>(elementcofigstr);
                    }

                }
            }
            return sameNodeConfig;
        }
        #endregion

        /// <summary>
        /// 将证据要素与事实要素的关系转到对应的模型上
        /// </summary>
        /// <param name="relationModes">关系列表</param>
        private void ConvertToEviFactElementRelationModel(List<DataModel> relationList)
        {
            if (dataContext.DataLayerOpt.EviFactElementRelations == null)
                dataContext.DataLayerOpt.EviFactElementRelations = new List<EviFactElementRelationModel>();
            foreach (DataModel dataModel in relationList.Where(a => a.XmlPath == @"证据事实要素关系/证据事实要素关系/详情"))
            {

                EviFactElementRelationModel eviFactElementRelation = new EviFactElementRelationModel();
                eviFactElementRelation.RelationId = dataModel.ID;
                AttributeInfo attribute = dataModel.AttributesList.Where(a => a.Name == "证据名称ID")?.First();
                if (attribute != null)
                {
                    eviFactElementRelation.EvidenceNameId = attribute.sourceList.Where(a => a.IsCheck == "1")?.First().SaveValue;
                    if (!string.IsNullOrEmpty(eviFactElementRelation.EvidenceNameId))
                    {
                        #region  查找证据节点  获取证据的证据地位、证据效力、证据效力来源的属性
                        var evidenceNodes = dataContext.DataLayerOpt.SourdatModleList.Where(a => a.ID == eviFactElementRelation.EvidenceNameId);
                        if (evidenceNodes != null && evidenceNodes.Count() > 0)
                        {
                            AttributeInfo attributeTemp = evidenceNodes.First().AttributesList.Where(a => a.Name == "证据地位").Count() > 0 ? evidenceNodes.First().AttributesList.Where(a => a.Name == "证据地位").First() : null;
                            if (attributeTemp != null)
                                eviFactElementRelation.EvidencePlace = attributeTemp.sourceList.Where(a => a.IsCheck == "1").Count() > 0 ? attributeTemp.sourceList.Where(a => a.IsCheck == "1").First().SaveValue : null;

                            attributeTemp = evidenceNodes.First().AttributesList.Where(a => a.Name == "证据效力").Count() > 0 ? evidenceNodes.First().AttributesList.Where(a => a.Name == "证据效力").First() : null;
                            if (attributeTemp != null)
                                eviFactElementRelation.EvidenceValidType = attributeTemp.sourceList.Where(a => a.IsCheck == "1").Count() > 0 ? attributeTemp.sourceList.Where(a => a.IsCheck == "1").First().SaveValue : null;

                            attributeTemp = evidenceNodes.First().AttributesList.Where(a => a.Name == "证据效力来源").Count() > 0 ? evidenceNodes.First().AttributesList.Where(a => a.Name == "证据效力来源").First() : null;
                            if (attributeTemp != null)
                                eviFactElementRelation.EvidenceValidSource = attributeTemp.sourceList.Where(a => a.IsCheck == "1").Count() > 0 ? attributeTemp.sourceList.Where(a => a.IsCheck == "1").First().SaveValue : null;
                        }
                        #endregion
                    }
                }
                eviFactElementRelation.EvidenceElementId = AttributesSelectValue(dataModel, "证据要素ID");
                eviFactElementRelation.FactElementId = AttributesSelectValue(dataModel, "事实要素ID");
                eviFactElementRelation.ElementType = AttributesSelectValue(dataModel, "要素分类");
                eviFactElementRelation.Xpath = AttributesSelectValue(dataModel, "xpath路径");
                eviFactElementRelation.RelationType = AttributesSelectValue(dataModel, "关系类型");
                if (!string.IsNullOrEmpty(eviFactElementRelation.EvidenceElementId))
                {
                    DataModel dataModelRoot = dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.ID == eviFactElementRelation.EvidenceNameId);
                    if (dataModelRoot != null)
                    {
                        DataModel dataModelRootPeron = dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.ID == dataModelRoot.ParentId);
                        if (dataModelRootPeron != null)
                        {
                            DataModel dataModelRootPeronModel = dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.ID == dataModelRootPeron.ParentId);
                            if (dataModelRootPeronModel != null)
                            {
                                eviFactElementRelation.ProponentName = AttributesSelectValue(dataModelRootPeronModel, "主张方姓名");
                                eviFactElementRelation.ProponentSituid = AttributesSelectValue(dataModelRootPeronModel, "主张方诉讼地位");
                            }
                        }
                    }
                }
                dataContext.DataLayerOpt.EviFactElementRelations.Add(eviFactElementRelation);

            }
        }

        /// <summary>
        /// 获取节点属性
        /// </summary>
        /// <param name="dataModel">节点</param>
        /// <param name="attName">属性名称</param>
        /// <returns></returns>
        private string AttributesSelectValue(DataModel dataModel, string attName)
        {
            string value = "";
            AttributeInfo attribute = dataModel.AttributesList.Where(a => a.Name == attName)?.First();
            if (attribute != null)
            {
                value = attribute.sourceList.Where(a => a.IsCheck == "1")?.First().SaveValue;
            }

            return value;
        }

        /// <summary>
        /// TODO:ZSW证据与事实要素关系建立
        /// 加载证据与事实要素关系数据
        /// </summary>
        /// <returns></returns>
        private List<RelationShip> LoadEvidFactRelations()
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon();
            List<RelationShip> resultRelations = new List<RelationShip>();
            if (dataContext.DataLayerOpt.EvidenceFactRelations != null && dataContext.DataLayerOpt.EvidenceFactRelations.Any())
            {
                #region 获取证据内容详情节点
                Dictionary<string, Tuple<string, string>> evidDic = new Dictionary<string, Tuple<string, string>>();
                var evidRootPath = $"{locationModel.DocPath}/证据相关信息";
                DataModel evidenRelationParentNode = XmlUtility.ConditionFirstOrDefaultDataModel(dataContext.DataLayerOpt.SourdatModleList, "", evidRootPath);
                var subEvidDatas = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, evidenRelationParentNode);
                var evidDataModels = subEvidDatas.Where(x => x.XmlPath.EndsWith("证据内容/详情")).ToList();
                if (evidDataModels != null && evidDataModels.Any())
                {
                    foreach (var evidItem in evidDataModels)
                    {
                        var sfidAttr = evidItem.AttributesList.FirstOrDefault(x => x.Name == "证据文件ID")?
                                             .sourceList?.Where(s => s.IsCheck == "1").FirstOrDefault()?.SaveValue;
                        if (!string.IsNullOrWhiteSpace(sfidAttr))
                        {
                            var evidSubDataModels = xmlUtilCommon.SubordinateDataModelList(subEvidDatas, evidItem);
                            if (evidSubDataModels != null && evidSubDataModels.Any())
                            {
                                
                                var evidSubIds = evidSubDataModels.Select(x => x.ID).ToList();
                                var firstFactData = dataContext.DataLayerOpt.EvidenceFactRelations.FirstOrDefault(x => x.EvidenceFileId == sfidAttr && evidSubIds.Contains(x.EvidenceElementId));
                                if (firstFactData != null)
                                {
                                    string factId = firstFactData.EvidenceElementId;
                                    if (evidSubIds.Contains(factId))
                                    {
                                        //获取证据要素Id
                                        string evidElement = evidSubDataModels.FirstOrDefault(x => x.XmlPath.EndsWith("证据要素"))?.ID;
                                        Tuple<string, string> evidTuple = new Tuple<string, string>(evidItem.ID, evidElement);
                                        evidDic.TryAdd(sfidAttr, evidTuple);
                                    }
                                }
                                
                            }
                        }
                    }
                }
                #endregion

                //分人员要素与证据节点对应关系
                var personRels = dataContext.DataLayerOpt.EvidenceFactRelations.Where(x => x.ElementType == "1").ToList();
                if (personRels != null && personRels.Any())
                {
                    foreach (var item in personRels)
                    {
                        var evidTupe = evidDic.GetValueOrDefault(item.EvidenceFileId);
                        //证据要素id
                        string evidElementId = evidTupe?.Item2;
                        //证据名称id
                        string evidNameId = evidTupe?.Item1;
                        //分人员要素Id
                        string personElementId = item.FactElenemtId;
                        //合并后要素Id
                        //获取合并后要素Id
                        var factRelRecord = dataContext.DataLayerOpt.EvidenceFactRelations.Where(x => x.ElementType == "2")
                                                      .Where(x => x.EvidenceFileId == item.EvidenceFileId)
                                                      .Where(x => x.Xpath == item.Xpath)
                                                      .Where(x => x.EvidenceElementId == item.EvidenceElementId)
                                                      .FirstOrDefault();
                        string mergerElementId = factRelRecord?.FactElenemtId;


                        //获取分人员要素节点属性
                        var itemNodeAttrs = dataContext.DataLayerOpt.SourdatModleList
                                                     .FirstOrDefault(x => x.ID == item.FactElenemtId)
                                                     ?.AttributesList
                                                     .Where(a => a.Name != "id")
                                                     .Select(x => x.Name).ToList();
                        if (itemNodeAttrs != null && itemNodeAttrs.Any())
                        {
                            foreach (var attrItem in itemNodeAttrs)
                            {
                                RelationShip relation = new RelationShip();
                                relation.XmlPath = $"{item.Xpath}/@{attrItem}";
                                relation.EvidenID = evidElementId;
                                relation.ElmentID = personElementId;
                                relation.EvidenNameID = evidNameId;
                                relation.Type = "1";
                                relation.ElementType = "1";
                                relation.MergerElementID = mergerElementId;
                                resultRelations.Add(relation);
                            }
                        }
                        else
                        {
                            RelationShip relation = new RelationShip();
                            relation.XmlPath = item.Xpath;
                            relation.EvidenID = evidElementId;
                            relation.ElmentID = personElementId;
                            relation.EvidenNameID = evidNameId;
                            relation.Type = "1";
                            relation.ElementType = "1";
                            relation.MergerElementID = mergerElementId;
                            resultRelations.Add(relation);
                        }
                    }
                }
            }
            return resultRelations;
        }
    }
}
